package main.gui.itemsdialog;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

import kassa.core.Kassa;

import main.core.Item;
import main.core.ItemArray;
import main.core.xml.XMLItems;
import main.core.xml.XMLItemsLoader;
import main.core.xml.XMLItemsSaver;

public class ItemsDialog extends JFrame implements ActionListener {

	private static final long serialVersionUID = 5818888994173576379L;
	private JPanel m_items;
	private JPanel m_setItemDatas;
	
	private static final String ADD_ONE = "Add one";
	private static final String LOAD = "Load...";
	private static final String OK = "OK";
	private static final String SAVE = "Save...";
	private static final String EXIT = "Exit";
	private static final int DEFAULT_NUMBER_ITEMS = 5;

	public ItemsDialog()
	{
		m_items = new JPanel();
		BoxLayout gl = new BoxLayout(m_items, BoxLayout.Y_AXIS);
		m_items.setLayout(gl);
		m_items.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		this.setResizable(false);

		//Insert header
		m_items.add(new SetItemData(true));
		
		//SetItemData elements
		m_setItemDatas = new JPanel();
		BoxLayout bl = new BoxLayout(m_setItemDatas, BoxLayout.Y_AXIS);
		m_setItemDatas.setLayout(bl);
		for(int i = 0; i < DEFAULT_NUMBER_ITEMS; ++i)
		{
			SetItemData itemData = new SetItemData(false);
			m_setItemDatas.add(itemData);
		}
		m_items.add(m_setItemDatas);
		
		
		m_items.add(getButtonPanel());
		
		this.setTitle("Add Items");
		this.setContentPane(m_items);
		this.pack();
	}
	
	private JPanel getButtonPanel()
	{
		//Buttons
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
		BoxLayout bs = new BoxLayout(buttonPanel, BoxLayout.X_AXIS);
		buttonPanel.setAlignmentX(JPanel.RIGHT_ALIGNMENT);
		buttonPanel.setLayout(bs);
		//Add one
		buttonPanel.add(getButton(ADD_ONE));
		//Load
		buttonPanel.add(getButton(LOAD));
		//Load
		buttonPanel.add(getButton(SAVE));
		//OK
		buttonPanel.add(getButton(OK));
		//Exit
		buttonPanel.add(getButton(EXIT));
		return buttonPanel;
	}
	
	private JButton getButton(String name)
	{
		JButton exit = new JButton(name);
		exit.addActionListener(this);
		return exit;
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		String cmd = event.getActionCommand();
		if(cmd.equals(ADD_ONE))
			add_one();
		else if(cmd.equals(LOAD))
			load();
		else if(cmd.equals(OK))
			ok();
		else if(cmd.equals(SAVE))
			save();
		else if(cmd.equals(EXIT))
			exit();
		else
			System.out.println(event.getActionCommand());
	}
	
	private void add_one()
	{
		SetItemData itemData = new SetItemData(false);
		m_setItemDatas.add("Player" + (m_setItemDatas.getComponentCount() + 1), itemData);
		this.pack();
	}
	
	private void save()
	{
		JFileChooser fs = new JFileChooser();
		//Show and accept .bpi files
		fs.setFileFilter(new FileFilter() {
			@Override
			public boolean accept(File f) {
				if(f.isDirectory())
					return true;
				int start_extension = f.getName().lastIndexOf('.');
				if(f.getName().lastIndexOf('.') < 0)
					return false;
				else
				{
					String extension = f.getName().substring(start_extension);
					if(extension.equals(".bpi"))
						return true;
				}
				return false;
			}

			@Override
			public String getDescription() {
			    return ".bpi files";
			}
		});
		int code = fs.showSaveDialog(this);
		if (code == JFileChooser.APPROVE_OPTION) {
            File file = fs.getSelectedFile();
            try {
            	ArrayList<Item> items = this.getItems();
            	//Save all items to filename file.getAbsolutePath()
            	String name = file.getAbsolutePath();
            	if(name.lastIndexOf(".bpi") == -1)
            		name += ".bpi";
            	XMLItemsSaver.saveFile(name, items, XMLItems.ITEMS_TYPE);
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	public ArrayList<Item> getItems()
	{
		ArrayList<Item> items = new ArrayList<Item>();
		for(int i = 0; i < m_setItemDatas.getComponentCount(); ++i)
		{
			SetItemData data = (SetItemData)m_setItemDatas.getComponent(i);
			Item item = null;
			if((item = data.getItem()) != null);
				items.add(item);
		}
		return items;
	}
	
	private void load()
	{
		JFileChooser fs = new JFileChooser();
		fs.setFileFilter(new FileFilter() {
			@Override
			public boolean accept(File f) {
				if(f.isDirectory())
					return true;
				int start_extension = f.getName().lastIndexOf('.');
				if(f.getName().lastIndexOf('.') < 0)
					return false;
				else
				{
					String extension = f.getName().substring(start_extension);
					if(extension.equals(".bpi"))
						return true;
				}
				return false;
			}

			@Override
			public String getDescription() {
			    return ".bpi files";
			}
		});
		int code = fs.showOpenDialog(this);
		if (code == JFileChooser.APPROVE_OPTION) {
            File file = fs.getSelectedFile();
            try {
				ArrayList<Item> items = XMLItemsLoader.loadFile(file, XMLItems.ITEMS_TYPE);
				int i = 0;
				Iterator<Item> it = items.iterator();
				while(it.hasNext())
				{
					Item cur_item = it.next();
					if(i >= DEFAULT_NUMBER_ITEMS)
						this.add_one();
					SetItemData data = (SetItemData)m_setItemDatas.getComponent(i);
					data.setItem(cur_item);
					++i;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
	}
	
	private void ok()
	{
		ItemArray.getInstance().setItems(this.getItems());
		Kassa kassa = new Kassa();
		
		this.setVisible(false);
		this.dispose();
	}
	
	private void exit()
	{
		this.setVisible(false);
		this.dispose();
	}
}
